from django.http import JsonResponse
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password
from utils.serializers import LoginSerializer
from django.views.decorators.csrf import csrf_exempt
from utils.crypto import DECRYPT
from utils.decorators import token_required
from device.models import Device
from django.core.cache import cache
import json
import ujson
from django.apps import apps  # 用于获取应用配置
from device.services.device_storage import DeviceStorage

@token_required
@csrf_exempt
def index(request):
    topic='/esp32/device/status'
    res = json.loads(request.body.decode('utf-8'))['secret']
    data = json.loads(DECRYPT.decrypt(res))
    sensor_data={
        'device_id':data.get('id'),
        'condition': data.get('condition'),
    }
    device = Device.objects.get(id=sensor_data['device_id'])
    if device.status!='online':
        secret = DECRYPT.encrypt({'status': 'success', 'message': '设备状态离线', 'code': 201})
        return JsonResponse({'secret': secret}, status=200)
    jons_str = ujson.dumps(sensor_data)
    publisher = apps.get_app_config('mqtt').mqtt_publisher
    success = publisher.publish(topic, jons_str)
    if success:
        device.condition = data.get('condition')
        device.save()
        store = DeviceStorage()
        store.delete_device()
        secret = DECRYPT.encrypt({'status': 'success', 'message': '操作成功','code': 200})
    else:
        secret = DECRYPT.encrypt({'status': 'success', 'message': '操作失败','code': 201})
    return JsonResponse({'secret':secret}, status=200)
